package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;
import org.elec.mac.entity.*;
import org.elec.mac.service.*;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Controller
public class DeviceMateController extends BaseController {

    @Autowired
    private SDeviceService deviceService;

    @Autowired
    private SDeviceMaterialService deviceMaterialService;

    @Autowired
    private SMaterialService sMaterialService;

    @Autowired
    private SMachineService sMachineService;

    @Autowired
    private SMachineMaterialService sMachineMaterialService;

    @Autowired
    private SBasicsFormulaService sBasicsFormulaService;

    @Autowired
    private SFormulaService sFormulaService;

    @RequestMapping(value = "/devicemate_list.do")
    public String deviceTechListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                        @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                        @RequestParam(value = "deviceid", required = false) String deviceid,
                                        @RequestParam(value = "limit", required = false) String limit,
                                        @RequestParam(value = "page", required = false) String page) throws IOException {
        Map<String, Object> param = new HashMap<>();
        Integer did = Utils.parseInt(deviceid, 0);
        param.put("did", did);
        param.put("sign", 0);
        List<Map<String, Object>> deviceMateList = deviceMaterialService.getDevicematerList(param);
        param.put("sign", 1);
        List<Map<String, Object>> deviceBasicList = deviceMaterialService.getDevicematerList(param);

        model.put("deviceBasicList", deviceBasicList);
        model.put("deviceMateList", deviceMateList);
        //待新增的原料
        List<SMaterial> materialList = sMaterialService.getDeviceMaterialInfo(did);
        model.put("materialList", materialList);
        param.clear();
        param.put("id", Utils.parseLong(deviceid, 0L));
        SDevice sDevice = deviceService.get(param);
        model.put("sDevice", sDevice);
        model.put("deviceid", Utils.parseLong(deviceid, 0L));
        return "/device/device_mate_list";
    }

    @RequestMapping(value = "/devicemate_add.do")
    public void deviceTechAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                     @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                     @RequestParam(value = "deviceid", required = false, defaultValue = "") String devideid)
            throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        Map<String, Object> param = new HashMap<>();
        if("do".equals(action)) {
            try {
                String did = request.getParameter("deviceid");
                String mid = request.getParameter("materiaid");
                SDeviceMaterial deviceMaterial = new SDeviceMaterial();
                deviceMaterial.setDid(Utils.parseLong(did,0));
                deviceMaterial.setMaid(Utils.parseLong(mid,0));
                deviceMaterialService.insert(deviceMaterial);
                //同时新增所有该设备机台的原料
                try {
                    param.put("id", mid);
                    SMaterial sMaterial = sMaterialService.get(param);
                    Integer amount = 1;
                    //判断是基础配方还是原料
                    if(null != sMaterial) {
                        if(sMaterial.getSign() == 1) {
                            amount = sBasicsFormulaService.getMaterialAmount(sMaterial.getId());
                        }
                    }
                    param.clear();
                    param.put("did", Utils.parseLong(did,0));
                    List<SMachine> machList = sMachineService.list(param);
                    if(machList.size() != 0) {
                        for (int i = 0; i < machList.size(); i++) {
                            SMachineMaterial machMaterial = new SMachineMaterial();
                            machMaterial.setMachid(machList.get(i).getId());
                            machMaterial.setMid(Utils.parseLong(mid,0));
                            machMaterial.setAmount(amount);
                            machMaterial.setWarning(1);
                            sMachineMaterialService.insert(machMaterial);
                        }
                        log.info("机台原料新增");
                    }
                } catch (Exception e) {
                    log.error("机台原料新增错误", e);
                    result.setSuccess(false);
                    result.setMsg("机台原料新增错误");
                }

            } catch(Exception ex) {
                log.error("设备原料新增错误", ex);
                result.setSuccess(false);
                result.setMsg("设备原料新增错误");
            }
        }

        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    //删除原料
    @RequestMapping(value = "/devicemate_detele.do")
    public void materialDeleteHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        Map<String, Object> params = new HashMap<>();
        Long deviceMaterId = Utils.parseLong(request.getParameter("id"), 0L);
        Long deviceId = Utils.parseLong(request.getParameter("deviceid"),0);
        params.put("id", deviceMaterId);
        SDeviceMaterial deviceMaterial = deviceMaterialService.get(params);

        try {
            params.clear();
            params.put("did", deviceId);
            //设备所有机台
            List<SMachine> machineList = sMachineService.list(params);
            if(machineList != null && machineList.size() != 0) {
                for (int i = 0; i < machineList.size(); i++) {
                    params.clear();
                    params.put("machid", machineList.get(i).getId());
                    //机台所有原料
                    List<SMachineMaterial> machineMaterials = sMachineMaterialService.list(params);
                    List<Map<String, Object>> sFormulaList = sFormulaService.getMachineMenuFormula(params);
                    for (Map item : sFormulaList) {
                        if(item.get("maid").equals(deviceMaterial.getMaid())) {//如果待删除的设备原料在机台菜单的产品当中，则不能删除
                            result.setSuccess(false);
                            result.setMsg("不能删除该设备原料");
                            break;
                        }
                    }
                    if(result.isSuccess()) {
                        for (int j = 0; j < machineMaterials.size(); j++) {
                            if(machineMaterials.get(j).getMid().equals(deviceMaterial.getMaid())) {//这里应该获取原料的ID
                                params.clear();
                                params.put("id", machineMaterials.get(j).getId());
                                sMachineMaterialService.delete(params);
                            }
                        }
                        try {
                            params.clear();
                            params.put("id", deviceMaterId);
                            deviceMaterialService.delete(params);
                            log.info("设备原料删除");
                        } catch(Exception ex) {
                            log.error("设备原料删除错误", ex);
                            result.setSuccess(false);
                            result.setMsg("设备原料删除错误");
                        }
                    }
                }
            }
            log.info("机台原料删除");
        } catch (Exception e) {
            log.error("机台原料删除错误", e);
            result.setSuccess(false);
            result.setMsg("机台原料删除错误");
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }
}
